<?php

namespace app\admin\service;

use app\model\MicroStory;
use app\model\Applet;

class MicroStoryService
{
    private $model;
    private $appletModel;

    public function __construct(MicroStory $model, Applet $appletModel)
    {
        $this->model = $model;
        $this->appletModel = $appletModel;
    }

    // 获取微故事列表
    public function getMicroStoryList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $data = $this->model->getPagingDataByWhere([], $page, $limit, 'id, applet_id, title, cover, author, is_release, created_at');

        // if ($data['data']) {
        //     $appletIds = array_column($data['data'], 'applet_id');

        //     $applets = $this->appletModel->getDataByWhere(['id' => $appletIds], 'id, name');
        //     $appletData = array_column($applets, 'name', 'id');

        //     foreach ($data['data'] as $key => $value) {
        //         $data['data'][$key]['applet_name'] = empty($appletData[$value['applet_id']]) ? '' : $appletData[$value['applet_id']];
        //     }
        // }

        return $data;
    }

    // 获取微故事详情
    public function getMicroStoryDetail($id)
    {
        $data = $this->model->getInfoByWhere(['id' => $id], 'id, applet_id, title, cover, author, content, is_release');

        return $data;
    }

    // 添加/修改微故事
    public function editMicroStory($params)
    {
        if (empty($params['id'])) {
            $params['created_at'] = time();
        } else {
            $params['updated_at'] = time();
        }

        $id = $this->model->edit($params);
        return $id ? true : false;
    }

    // 删除微故事
    public function deleteMicroStory($id)
    {
        $bool = $this->model->destroy($id);

        return $bool ? true : false;
    }
}